<template>
  <n-form
    v-if="model && data"
    :model="data"
    label-placement="left"
    label-width="5em"
    label-align="left"
  >
    <template v-for="[k, v] of Object.entries(model)" :key="k">
      <n-form-item v-if="k != `About`" :label="replaceName(k)">
        <n-select
          v-if="connection?.[k] != null"
          v-model:value="data[k]"
          :options="connection?.[k]"
        ></n-select>
        <my-input
          v-else
          :field="k"
          :type="v"
          v-model:value="data[k]"
        ></my-input>
      </n-form-item>
      <about v-else-if="data[k] != null" :value="data[k]" :type="v"></about>
    </template>
    <div style="text-align: right">
      <n-button @click="onSubmit" type="primary" size="large" style=""
        >提交</n-button
      >
      <n-button
        @click="() => router.push(`/${props.resource}/list`)"
        style="margin-left: 3em"
        strong
        secondary
        size="large"
        >返回</n-button
      >
    </div>
  </n-form>
</template>

<script lang="ts" setup>
import { NForm, NFormItem, NSelect, NButton } from "naive-ui";
import { useMessage } from "naive-ui";
import { useRouter } from "vue-router";

import { useModel, useData } from "@/api/CRUD";
import { replaceName } from "@/data";
import MyInput from "@/components/Form/Input.vue";
import About from "@/components/Form/About.vue";

// 接收
const props = defineProps<{
  resource: string;
  id?: string;
}>();

// 初始化所需对象
const message = useMessage();
const router = useRouter();

// 获取数据及对应方法
const { model, connection, getModel } = useModel(props.resource);
const { data, find, create, update } = useData(props.resource);

// 提交事件
async function onSubmit() {
  let msg: string;
  if (props.id) {
    msg = await update(props.id);
  } else {
    msg = await create();
  }
  message.success(msg);
  router.back();
}

// 组件创建调用
(async () => {
  await getModel();
  if (props.id) {
    await find(props.id);
  }
})();
</script>
